<!-- <template>
    <div>
     <div style="align-items: center;height: 70px;">
      <div class="nav">
        <router-link to="/detail">收入</router-link> |
        <router-link to="/detail2">支出</router-link>
      </div>
     </div>
      <h1>This is a detail2 page</h1>
    </div>
  </template>
  
  <script>
  export default {
    name: 'Detail2View',
    inject: ['$router'],
    // ...
  }
  </script>

  <style>
  .nav {
    padding: 30px;
  }
  
  .nav a {
    font-weight: bold;
    color: #2c3e50;
  }
  
  .nav a.router-link-exact-active {
    /* color: #42b983; */
    color: white;
  }
  </style> -->

  <template>
    <div>
      <div class="nav">
        <!-- <button @click="goBack">返回</button> -->
        <router-link to="/detail">收入</router-link> |
        <router-link to="/detail2">支出</router-link>
      </div>
      <!-- <van-cell title="选择单个日期" :value="date" @click="show = true" />
      <van-calendar v-model="show" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" /> -->
      <van-cell title="选择年月" :value="date" @click="show = true" />
      <van-popup v-model="show" position="top"
        ><div>
      <van-datetime-picker
        v-model="currentDate"
        type="year-month"
        title="选择年月"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="confirmClick"
        @cancel="cancelClick"
      /></div
      ></van-popup>

      <div class="echart" id="mychart" :style="myChartStyle"></div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- <van-cell v-for="item in dataDict" :key="item" :title="item" />
         -->
         <van-cell v-for="(item, index) in dataDict2" :key="index">
            <!-- {{ item }} - {{ yData[index] }} -->
            <!-- {{ item }} 收入：{{ yData[index] }}元 -->
            {{`${index}`}} &nbsp;&nbsp; &nbsp;&nbsp;{{ `收入：${item[0]}元` }} &nbsp;&nbsp;&nbsp;&nbsp;{{ `笔数：${item[1]}笔`
            }}
          </van-cell>
        </van-list>
      <div style="">
   
      </div>

    </div>
  </template>
    
  <script>
  import * as echarts from "echarts";
  import { Calendar } from 'vant';
  const monthDays = Array.from({ length: 30 }, (_, index) => index + 1);
  
  export default {
    data() {
      return {
        // 年月
        // show: true,
        selectYear: 2023,
        selectMonth:8,
        // 选择日期
        date: '',
        show: false,
        // show: false,
        currentDate: new Date(),
        minDate: new Date(2022, 4, 3),
        maxDate: new Date(),
        // 列表
        list: [],
        loading: false,
        finished: false,
        // 表格数据
        xData: [], // 修改为动态计算的日期数组
        yData: [],
        zData: [],
        myChartStyle: { float:"right", width: "100%", height: "300px" },// 图表样式
        dateList: [], // 新增日期数组
        // dateList: this.$route.params.dateList.reverse(),
        dataDict:{},
        dataDict2:{},
        yyData:[],
        zzData:[],
        // 列表
        list: [],
        loading: false,
        finished: false,
      };
    },

    async mounted() {
      await this.getData();  
      this.generateDateList();

      // this.initDate();
      // this.initEcharts();
      
      // console.log(this.yData);
    },
    methods: {
      // 表
      onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1);
        }

        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if (this.list.length >= 40) {
          this.finished = true;
        }
      }, 1000);
      },
      // 定义图
      initEcharts(){  
        // 基本折线图
        const option = {
          xAxis: {
            data: this.xxData,
          },
          yAxis: {
            data: [],
            type :'value',
            // data: this.yyData,
          },
          grid:{
            left:'20',
            containLabel:true,
          },
          series: [
            {
              type: "bar", 
              data: this.yyData,
              itemStyle: {
                color: 'rgb(24, 144, 255)'
              },
              areaStyle: { // 设置阴影区域的颜色和透明度
                color: 'rgba(24, 144, 255, 0.3)'
              }
            }
          ]
        };
  
        const myChart = echarts.init(document.getElementById("mychart"));
  
  
        // console.log(this.xData)
        myChart.setOption(option);
  
        // 随着屏幕大小调节图表
        window.addEventListener("resize", () => {
          myChart.resize();
        });
      },

      // 连接数据库
      async getData() {
        // let dataDict = {};
        // const url = "http://127.0.0.1:8081/merchanthome/details?id=1&year=2023&month=6"
        const url = `http://127.0.0.1:8081/merchanthome/details?id=1&year=${this.selectYear}&month=${this.selectMonth}`
        console.log('url',url);
        const { code, data } = await this.$http.get(
          url
        );
        console.log('data',data);
        // 交易日
        const tradingDays = data.data.map(item => {
          const day = item.trading_day.split("-")[2];
          return parseInt(day);
        });
        console.log('xData ',tradingDays);
        this.xData = tradingDays;
        // 金额
        // const incomeAmount = data.data.map(item => {
        //   const income = item.income_amount.split("-")[1];
        //   return parseInt(income);
        // });
        const incomeAmount = data.data.map(item => item.income_amount || 0);
        console.log('yData ',incomeAmount);
        this.yData = incomeAmount;
        // 笔数 
        // const incomeCount = data.data.map(item => {
        //   const count = item.income_count.split("-")[1];
        //   return parseInt(count);
        // });
        const incomeCount = data.data.map(item => item.income_count || 0);
        console.log('zData ',incomeCount);
        this.zData = incomeCount;
        // 修改格式
        // 将xData和yData、zData关联为字典
        const dataDict = this.xData.reduce((dict, x, index) => {
          dict[x] = [this.yData[index],this.zData[index]];
          return dict;
        }, {});
        this.dataDict = dataDict;

        // 打印关联后的字典
        console.log('1111',dataDict);

      },


      // 年月选择器
      async confirmClick(value) {
        this.selectYear = value.getFullYear();
        this.selectMonth = value.getMonth() + 1;
        this.show = false;
        await this.getData();
        this.generateDateList();
        // this.initEcharts();
      },
      cancelClick() {
        this.show = false;
      },
      formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      }
      return val;
      }, 

      generateDateList() {
        console.log('执行一次');
        const currentDate = new Date();
        const currentDay = currentDate.getDate();
        const currentMonth = currentDate.getMonth() + 1;
        console.log(currentDate);
        // const totalDays = new Date(this.selectYear, this.selectMonth, 0).getDate();
        // const totalDays = Math.min(currentDay, new Date(this.selectYear, this.selectMonth, 0).getDate()); 
        let totalDays;
        if (currentMonth === this.selectMonth) {
          totalDays = Math.min(currentDay, new Date(this.selectYear, this.selectMonth, 0).getDate());
        } else {
          totalDays = new Date(this.selectYear, this.selectMonth, 0).getDate();
        }
        console.log(totalDays)
        this.xxData = Array.from({ length: totalDays }, (_, index) => `${this.selectMonth}月${index + 1}日`);
        // this.xxData = Array.from({ length: totalDays }, (_, index) => `${index+1}`);
        this.xxData = this.xxData.map(date => {
          const day = date.split('月')[1].split('日')[0];
          return parseInt(day);
        });
        console.log('xxData', this.xxData);
        // console.log(this.dataDict);
        this.yyData = this.xxData.map(date => {
          const value = this.dataDict[date] ? this.dataDict[date][0] : 0;
          return value;
        });
        console.log('yyData', this.yyData);
        this.zzData = this.xxData.map(date => {
          const value = this.dataDict[date] ? this.dataDict[date][1] : 0;
          return value;
        });
        console.log('zzData', this.zzData);
        this.initEcharts();
        // 转换格式
        const dataDict2 = this.xxData.reverse().reduce((dict, x, index) => {
          dict[`${this.selectMonth}月${x}日`] = [this.yyData.reverse()[index],this.zzData.reverse()[index]];
          return dict;
        }, {});
        this.dataDict2 = dataDict2;
        console.log('dataDict2', this.dataDict2);
        console.log('xx',this.xxData);
      },
    },
  };
  </script>
    
    <!-- 文首链接 -->
  <style>
  .nav {
    padding: 30px;
  }
  
  .nav a {
    font-weight: bold;
    color: #2c3e50;
  }
  
  .nav a.router-link-exact-active {
    /* color: #42b983; */
    color: white;
  }
  </style>
    